<template>
  <div class="app-container">
    <el-card>
      <!-- 头部 -->
      <el-row type="flex">
        <el-col>
          <el-form ref="searchData">
            <el-form-item label="学科名称">
              <el-input
                v-model.trim="searchData"
                size="small"
                style="width: 200px; margin-right: 10px"
              />
              <el-button size="small" @click="clearData">清除</el-button>
              <el-button
                size="small"
                type="primary"
                @click="searchBtn"
              >搜索</el-button>
            </el-form-item>
          </el-form>
        </el-col>

        <el-row type="flex" justify="right">
          <el-col>
            <el-button
              size="small"
              type="success"
              icon="el-icon-edit"
              @click="addSubject"
            >新增学科</el-button>
          </el-col>
        </el-row>
      </el-row>
      <el-alert
        :title="'数据一共 ' + page.total + ' 条'"
        type="info"
        :closable="false"
        show-icon
        style="margin-bottom: 20px"
      />
      <!-- 表格 -->
      <el-table
        :header-cell-style="{
          background: '#fafafa',
          borderBottom: '3px solid #ebeef5',
        }"
        :data="list"
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" />
        <el-table-column prop="subjectName" label="学科名称" />
        <el-table-column prop="username" label="创建者" />
        <el-table-column prop="addDate" label="创建日期" :formatter="formatterTime" />
        <el-table-column prop="isFrontDisplay" label="后台是否显示" :formatter="formatIsFrontDisplay" />
        <el-table-column prop="twoLevelDirectory" label="二级目录" />
        <el-table-column prop="tags" label="标签" />
        <el-table-column prop="totals" label="题目数量" />
        <el-table-column fixed="right" label="操作" width="250">
          <template v-slot="scope">
            <el-button type="text" size="small" @click="toDirectorys('subject')">学科分类</el-button>
            <el-button type="text" size="small" @click="toTags('subject')">学科标签</el-button>
            <el-button
              type="text"
              size="small"
              @click="editSubject(scope.row.id)"
            >修改</el-button>
            <el-button
              type="text"
              size="small"
              @click="delSubject(scope.row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-row type="flex" justify="end" align="middle" style="height: 60px">
        <el-pagination
          :page-sizes="[5, 10, 20, 50]"
          background
          layout="sizes,prev,pager,next,jumper"
          :page-size="page.pagesize"
          :current-page="page.page"
          :total="page.total"
          @current-change="changePage"
          @size-change="sizeChange"
        />
      </el-row>
      <!-- 弹框 -->
      <el-dialog
        width="30%"
        :title="title"
        :visible="dialogFormVisible"
        @close="cancelBtn"
      >
        <el-form ref="formData" :model="formData" :rules="rules">
          <el-form-item prop="subjectName" label="学科名称" label-width="80px">
            <el-input v-model="formData.subjectName" />
          </el-form-item>
          <el-form-item label="是否显示" label-width="80px">
            <el-switch
              v-model="formData.isFrontDisplay"
              active-color="#13ce66"
              inactive-color="#ff4949"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button size="small" @click="cancelBtn">取 消</el-button>
          <el-button
            size="small"
            type="primary"
            @click="subBtn"
          >确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import {
  getSubjectList,
  addSubject,
  delSubject,
  editSubject,
  getSubjectDetail
} from '@/api/subject'
import { formateTime } from '@/filter/formateTime'
export default {
  data() {
    return {
      list: [],
      page: {
        page: 1,
        pagesize: 5,
        total: 0
      },
      formData: {
        subjectName: '',
        isFrontDisplay: ''
      },
      dialogFormVisible: false,
      rules: {
        subjectName: [
          { required: true, message: '学科名称不能为空', trigger: 'blur' }
        ]
      },
      searchData: ''
    }
  },
  computed: {
    title() {
      return this.formData.id ? '修改学科' : '新增学科'
    }
  },
  created() {
    this.getSubjectList(this.page)
  },
  methods: {

    // 获得学科列表
    async getSubjectList(data) {
      const res = await getSubjectList(data)
      this.list = res.items
      this.page.total = res.counts
    },
    // 切换分页
    async changePage(val) {
      this.page.page = val
      await this.getSubjectList(this.page)
    },
    async sizeChange(val) {
      this.page.pagesize = val
      await this.getSubjectList(this.page)
    },
    // 新增学科
    addSubject() {
      this.dialogFormVisible = true
    },
    // 确定按钮 提交表单
    async subBtn() {
      await this.$refs.formData.validate()
      this.formData.isFrontDisplay =
        this.formData.isFrontDisplay === true ? 1 : 0
      try {
        if (this.formData.id) {
          await editSubject(this.formData)
        } else {
          await addSubject(this.formData)
        }
        this.getSubjectList(this.page)
        this.$message.success('操作成功')
        this.dialogFormVisible = false
      } catch (err) {
        this.$message.error(err, '操作失败')
      }
    },
    // 取消按钮
    cancelBtn() {
      this.$refs.formData.resetFields()
      this.formData = {
        subjectName: '',
        isFrontDisplay: ''
      }
      this.dialogFormVisible = false
    },
    // 删除按钮 删除学科
    async delSubject(id) {
      try {
        await this.$confirm('此操作将永久删除该文件, 是否继续?')
        await delSubject(id)
        this.isLastItem()
        this.getSubjectList(this.page)
        this.$message.success('删除成功')
      } catch (err) {
        this.$message.error(err, '删除失败')
      }
    },
    // 检验删除后是否为最后一项数据
    isLastItem() {
      // 删除一项后的真实页面数
      const totalPage = Math.ceil((this.page.total - 1) / this.page.pagesize)
      // 判断当前页面数和真实页面数的大小
      const total = this.page.page > totalPage ? totalPage : this.page.page
      // 判断是否为第一页
      this.page.page = total < 1 ? 1 : total
    },
    // 修改按钮 修改学科
    async editSubject(id) {
      this.formData = await getSubjectDetail(id)
      this.formData.isFrontDisplay = this.formData.isFrontDisplay === 1
      this.dialogFormVisible = true
    },
    // 搜索按钮
    searchBtn() {
      if (this.searchData) {
        this.getSubjectList({ ...this.page, subjectName: this.searchData })
      } else {
        this.$message.warning('搜索不能为空')
      }
    },
    // 清除按钮 清除输入框内容
    clearData() {
      this.getSubjectList(this.page)
      this.searchData = ''
    },
    // 学科分类按钮 跳转到目录
    toDirectorys(id) {
      this.$router.push({
        path: `subject/directorys/${id}`
      })
    },
    // 学科标签按钮 跳转到标签
    toTags(id) {
      this.$router.push({
        path: `subject/tags/${id}`
      })
    },
    // 时间格式化
    formatterTime(row, column, cellValue, index) {
      return formateTime(cellValue)
    },
    // 后台是否显示 格式化
    formatIsFrontDisplay(row, column, cellValue, index) {
      return cellValue === 1 ? '是' : '否'
    }
  }
}
</script>

<style lang="scss">
// 对话框样式

.el-dialog__wrapper {
  .el-dialog {
    overflow: hidden;
    border-radius: 10px;
    .el-dialog__header {
      background: #409eff;
      .el-dialog__title {
        color: white;
      }
      .el-icon-close::before {
        color: white;
      }
    }
  }
}
</style>
